import { useState, useEffect, useRef } from 'react';
import { Link } from 'react-router-dom';
import { MenuIcon, X, ChevronDown, ShoppingCart } from 'lucide-react';
import Button from './Button';
import LanguageSwitcher from './LanguageSwitcher';
import ThemeSwitcher from './ThemeSwitcher';
import { useLanguage } from '../contexts/LanguageContext';
import { useCart } from '../contexts/CartContext';

const Navbar = () => {
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [isScrolled, setIsScrolled] = useState(false);
  const [isPricingOpen, setIsPricingOpen] = useState(false);
  const [isPurchaseOpen, setIsPurchaseOpen] = useState(false);
  const { language, t } = useLanguage();
  const { getItemCount } = useCart();
  const pricingRef = useRef<HTMLDivElement>(null);
  const purchaseRef = useRef<HTMLDivElement>(null);

  // Detect scroll position
  useEffect(() => {
    const handleScroll = () => {
      const scrollPosition = window.scrollY;
      setIsScrolled(scrollPosition > 20);
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  // Close pricing dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (pricingRef.current && !pricingRef.current.contains(event.target as Node)) {
        setIsPricingOpen(false);
      }
      if (purchaseRef.current && !purchaseRef.current.contains(event.target as Node)) {
        setIsPurchaseOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Helper function to create language-aware links
  const getLink = (path: string) => {
    return language === 'zh-CN' ? `/zh-CN${path}` : path;
  };

  return (
    <header 
      className={`text-white sticky top-0 z-50 transition-all duration-300 ${
        isScrolled 
          ? 'bg-[#0f1c3f]/80 dark:bg-gray-900/80 backdrop-blur-xl shadow-lg border-b border-white/10 dark:border-gray-700/50' 
          : 'bg-[#0f1c3f] dark:bg-gray-900'
      }`}
    >
      <div className="container mx-auto px-4 py-4 flex justify-between items-center">
        <Link to={getLink('/')} className="flex items-center space-x-2">
          <img src="/logo.svg" alt="KernelProxy" className="w-8 h-8" />
          <div className="flex items-center">
            <span className="text-2xl font-bold text-[#00d4ff]">kernel</span>
            <span className="text-2xl font-bold">Proxy</span>
          </div>
        </Link>

        {/* Desktop Navigation */}
        <nav className="hidden md:flex items-center space-x-8">
          <Link to={getLink('/products')} className="hover:text-[#00d4ff] transition-colors">
            {t('nav.products')}
          </Link>
          
          {/* Pricing Dropdown */}
          <div className="relative" ref={pricingRef}>
            <button
              className="flex items-center space-x-1 hover:text-[#00d4ff] transition-colors"
              onClick={() => {
                setIsPricingOpen(!isPricingOpen);
                setIsPurchaseOpen(false);
              }}
              onMouseEnter={() => {
                setIsPricingOpen(true);
                setIsPurchaseOpen(false);
              }}
            >
              <span>{t('nav.pricing')}</span>
              <ChevronDown size={16} className={`transition-transform duration-200 ${isPricingOpen ? 'rotate-180' : ''}`} />
            </button>
            
            {isPricingOpen && (
              <div 
                className="absolute top-full left-0 mt-2 w-64 bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-700 py-2 z-50"
                onMouseLeave={() => setIsPricingOpen(false)}
              >
                <Link
                  to={getLink('/pricing/dynamic-residential-ipv6')}
                  className="block px-4 py-3 text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700 hover:text-[#00d4ff] transition-colors"
                  onClick={() => setIsPricingOpen(false)}
                >
                  <div className="font-medium">{t('nav.pricingMenu.dynamic.title')}</div>
                  <div className="text-xs text-gray-500 dark:text-gray-400">{t('nav.pricingMenu.dynamic.subtitle')}</div>
                </Link>
                <Link
                  to={getLink('/pricing/static-residential-ipv6')}
                  className="block px-4 py-3 text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700 hover:text-[#00d4ff] transition-colors"
                  onClick={() => setIsPricingOpen(false)}
                >
                  <div className="font-medium">{t('nav.pricingMenu.static.title')}</div>
                  <div className="text-xs text-gray-500 dark:text-gray-400">{t('nav.pricingMenu.static.subtitle')}</div>
                </Link>
                <Link
                  to={getLink('/pricing/datacenter-ipv6')}
                  className="block px-4 py-3 text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700 hover:text-[#00d4ff] transition-colors"
                  onClick={() => setIsPricingOpen(false)}
                >
                  <div className="font-medium">{t('nav.pricingMenu.datacenter.title')}</div>
                  <div className="text-xs text-gray-500 dark:text-gray-400">{t('nav.pricingMenu.datacenter.subtitle')}</div>
                </Link>
              </div>
            )}
          </div>

          {/* Purchase Dropdown */}
          <div className="relative" ref={purchaseRef}>
            <button
              className="flex items-center space-x-1 hover:text-[#00d4ff] transition-colors"
              onClick={() => {
                setIsPurchaseOpen(!isPurchaseOpen);
                setIsPricingOpen(false);
              }}
              onMouseEnter={() => {
                setIsPurchaseOpen(true);
                setIsPricingOpen(false);
              }}
            >
              <span>{language === 'zh-CN' ? '选购' : 'Purchase'}</span>
              <ChevronDown size={16} className={`transition-transform duration-200 ${isPurchaseOpen ? 'rotate-180' : ''}`} />
            </button>
            
            {isPurchaseOpen && (
              <div 
                className="absolute top-full left-0 mt-2 w-64 bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-700 py-2 z-50"
                onMouseLeave={() => setIsPurchaseOpen(false)}
              >
                <Link
                  to={getLink('/pricing/purchase-dynamic-residential')}
                  className="block px-4 py-3 text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700 hover:text-[#00d4ff] transition-colors"
                  onClick={() => setIsPurchaseOpen(false)}
                >
                  <div className="font-medium">{language === 'zh-CN' ? '动态住宅 IPv6' : 'Dynamic Residential IPv6'}</div>
                  <div className="text-xs text-gray-500 dark:text-gray-400">{language === 'zh-CN' ? '按流量计费' : 'Traffic-based pricing'}</div>
                </Link>
                <Link
                  to={getLink('/pricing/purchase-static-residential')}
                  className="block px-4 py-3 text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700 hover:text-[#00d4ff] transition-colors"
                  onClick={() => setIsPurchaseOpen(false)}
                >
                  <div className="font-medium">{language === 'zh-CN' ? '静态住宅 IPv6' : 'Static Residential IPv6'}</div>
                  <div className="text-xs text-gray-500 dark:text-gray-400">{language === 'zh-CN' ? '固定IP' : 'Fixed IPs'}</div>
                </Link>
                <Link
                  to={getLink('/pricing/purchase-datacenter')}
                  className="block px-4 py-3 text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700 hover:text-[#00d4ff] transition-colors"
                  onClick={() => setIsPurchaseOpen(false)}
                >
                  <div className="font-medium">{language === 'zh-CN' ? '数据中心 IPv6' : 'Datacenter IPv6'}</div>
                  <div className="text-xs text-gray-500 dark:text-gray-400">{language === 'zh-CN' ? '高速稳定' : 'Fast & Stable'}</div>
                </Link>
              </div>
            )}
          </div>

          <Link to={getLink('/documentation')} className="hover:text-[#00d4ff] transition-colors">
            {t('nav.documentation')}
          </Link>
          <Link to={getLink('/blog')} className="hover:text-[#00d4ff] transition-colors">
            {t('nav.blog')}
          </Link>
          <Link to={getLink('/support')} className="hover:text-[#00d4ff] transition-colors">
            {t('nav.support')}
          </Link>
        </nav>

        <div className="hidden md:flex items-center space-x-4">
          <LanguageSwitcher />
          <ThemeSwitcher />
          
          {/* Shopping Cart */}
          <Link 
            to={getLink('/cart')} 
            className="relative text-white hover:text-[#00d4ff] transition-colors p-2"
            title={language === 'zh-CN' ? '购物车' : 'Shopping Cart'}
          >
            <ShoppingCart size={24} />
            {getItemCount() > 0 && (
              <span className="absolute -top-1 -right-1 bg-[#00d4ff] text-[#0f1c3f] text-xs font-bold rounded-full w-5 h-5 flex items-center justify-center">
                {getItemCount()}
              </span>
            )}
          </Link>
          
          <a href="http://localhost:5175/login">
            <Button variant="gradient">{t('nav.login')}</Button>
          </a>
        </div>

        {/* Mobile menu button */}
        <button
          className="md:hidden text-white"
          onClick={() => setIsMenuOpen(!isMenuOpen)}
        >
          {isMenuOpen ? <X size={24} /> : <MenuIcon size={24} />}
        </button>
      </div>

      {/* Mobile Navigation */}
      {isMenuOpen && (
        <div className={`md:hidden py-4 transition-all duration-300 ${
          isScrolled 
            ? 'bg-[#0f1c3f]/95 dark:bg-gray-900/95 backdrop-blur-xl border-t border-white/10 dark:border-gray-700/50' 
            : 'bg-[#0f1c3f] dark:bg-gray-900'
        }`}>
          <div className="container mx-auto px-4 flex flex-col space-y-4">
            <Link
              to={getLink('/products')}
              className="block py-2 hover:text-[#00d4ff]"
              onClick={() => setIsMenuOpen(false)}
            >
              {t('nav.products')}
            </Link>
            
            {/* Pricing Submenu */}
            <div className="space-y-2">
              <div className="text-gray-400 text-sm font-medium px-2">
                {t('nav.pricing')}
              </div>
              <Link
                to={getLink('/pricing/dynamic-residential-ipv6')}
                className="block py-2 pl-4 hover:text-[#00d4ff]"
                onClick={() => setIsMenuOpen(false)}
              >
                <div>{t('nav.pricingMenu.dynamic.title')}</div>
                <div className="text-xs text-gray-400">{t('nav.pricingMenu.dynamic.subtitle')}</div>
              </Link>
              <Link
                to={getLink('/pricing/static-residential-ipv6')}
                className="block py-2 pl-4 hover:text-[#00d4ff]"
                onClick={() => setIsMenuOpen(false)}
              >
                <div>{t('nav.pricingMenu.static.title')}</div>
                <div className="text-xs text-gray-400">{t('nav.pricingMenu.static.subtitle')}</div>
              </Link>
              <Link
                to={getLink('/pricing/datacenter-ipv6')}
                className="block py-2 pl-4 hover:text-[#00d4ff]"
                onClick={() => setIsMenuOpen(false)}
              >
                <div>{t('nav.pricingMenu.datacenter.title')}</div>
                <div className="text-xs text-gray-400">{t('nav.pricingMenu.datacenter.subtitle')}</div>
              </Link>
            </div>

            {/* Purchase Submenu */}
            <div className="space-y-2">
              <div className="text-gray-400 text-sm font-medium px-2">
                {language === 'zh-CN' ? '选购' : 'Purchase'}
              </div>
              <Link
                to={getLink('/pricing/purchase-dynamic-residential')}
                className="block py-2 pl-4 hover:text-[#00d4ff]"
                onClick={() => setIsMenuOpen(false)}
              >
                <div>{language === 'zh-CN' ? '动态住宅 IPv6' : 'Dynamic Residential IPv6'}</div>
                <div className="text-xs text-gray-400">{language === 'zh-CN' ? '按流量计费' : 'Traffic-based pricing'}</div>
              </Link>
              <Link
                to={getLink('/pricing/purchase-static-residential')}
                className="block py-2 pl-4 hover:text-[#00d4ff]"
                onClick={() => setIsMenuOpen(false)}
              >
                <div>{language === 'zh-CN' ? '静态住宅 IPv6' : 'Static Residential IPv6'}</div>
                <div className="text-xs text-gray-400">{language === 'zh-CN' ? '固定IP' : 'Fixed IPs'}</div>
              </Link>
              <Link
                to={getLink('/pricing/purchase-datacenter')}
                className="block py-2 pl-4 hover:text-[#00d4ff]"
                onClick={() => setIsMenuOpen(false)}
              >
                <div>{language === 'zh-CN' ? '数据中心 IPv6' : 'Datacenter IPv6'}</div>
                <div className="text-xs text-gray-400">{language === 'zh-CN' ? '高速稳定' : 'Fast & Stable'}</div>
              </Link>
            </div>

            <Link
              to={getLink('/documentation')}
              className="block py-2 hover:text-[#00d4ff]"
              onClick={() => setIsMenuOpen(false)}
            >
              {t('nav.documentation')}
            </Link>
            <Link
              to={getLink('/blog')}
              className="block py-2 hover:text-[#00d4ff]"
              onClick={() => setIsMenuOpen(false)}
            >
              {t('nav.blog')}
            </Link>
            <Link
              to={getLink('/support')}
              className="block py-2 hover:text-[#00d4ff]"
              onClick={() => setIsMenuOpen(false)}
            >
              {t('nav.support')}
            </Link>
            
            {/* Shopping Cart for Mobile */}
            <Link
              to={getLink('/cart')}
              className="block py-2 hover:text-[#00d4ff] flex items-center justify-between"
              onClick={() => setIsMenuOpen(false)}
            >
              <span className="flex items-center gap-2">
                <ShoppingCart size={20} />
                {language === 'zh-CN' ? '购物车' : 'Shopping Cart'}
              </span>
              {getItemCount() > 0 && (
                <span className="bg-[#00d4ff] text-[#0f1c3f] text-xs font-bold rounded-full w-5 h-5 flex items-center justify-center">
                  {getItemCount()}
                </span>
              )}
            </Link>
            
            <div className="pt-2 border-t border-gray-700">
              <LanguageSwitcher />
            </div>
            <div className="pt-2">
              <ThemeSwitcher />
            </div>
            <div className="pt-4">
              <a href="http://localhost:5175/login">
                <Button variant="gradient" fullWidth>
                  {t('nav.login')}
                </Button>
              </a>
            </div>
          </div>
        </div>
      )}
    </header>
  );
};

export default Navbar;